package com.hoperun.product.activity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hoperun.product.adapter.QueryListAdapter;
import com.hoperun.product.adapter.QueryListAdapter.onCheckClickListener;
import com.hoperun.product.base.MIP_BaseActivity;
import com.hoperun.product.common.TableNo;
import com.hoperun.product.entity.ProductInputEntity;
import com.hoperun.product.entity.ProductQueryEntity;
import com.hoperun.product.entity.SpinnerEntity;
import com.hoperun.product.net.IServiceImpl;
import com.hoperun.product.net.RequestServiceImpl;
import com.hoperun.product.util.ParseUtils;
import com.hoperun.product.util.SharedPreUtil;
import com.hoperun.product.view.SimpleDialog;
import com.hoperun.yieldmgryue.R;

public class QueryActivity extends MIP_BaseActivity implements OnClickListener {
	// 日期布局
	private LinearLayout mDateLl;
	// 日期
	private TextView mDateTv;

	// 工号
	private EditText mJobNumEt;
	// 车号
	private EditText mMachineNoEt;
	
	/******2017年12月4日 修改，去掉车间选择框*********/
	// 车间 下拉框
	//private Spinner mBmmcSp;
	// 班次 下拉框
	private Spinner mClassesSp;

	// 无标准定额
	private CheckBox mCheckBox;

	// 查询
	private Button mQueryBtn;
	// 保存
	private Button mSaveBtn;
	// 返回
	private Button mBackBtn;

	private TextView mCountTv;
	private TextView mCountTv2;
	private ListView mListView;
	// 暂无数据图片
	private ImageView nodateImg;
	// 存储日期
	private String mJobDate = "";

	private List<String> mBmmcList = new ArrayList<String>();
	private ArrayAdapter<String> mBmmcSpAdapter;
	private int mYear;

	private int mMonth;

	private int mDay;
	//private SimpleDateFormat dateFormat_ZH = new SimpleDateFormat("yyyy年MM月dd日");	
	private SimpleDateFormat dateFormat_EN = new SimpleDateFormat("yyyy-MM-dd");
	// 保存按钮权限
	private String mSaveQX = "";

	private List<ProductQueryEntity> mProductList = new ArrayList<ProductQueryEntity>();
	// 保存需要上传服务器的list
	private List<ProductQueryEntity> mSaveProductList = new ArrayList<ProductQueryEntity>();

	private QueryListAdapter mAdapter;

	// 记录当前选择的项数
	private int mCount;

	/** 无标准定额 勾了 为1 ，不勾选为0 **/
	private String mStandardQuota = "0";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.query_activity);
		initDate();
		initView();
		initEvent();
		selectDict();
		//getQueryList(mJobDate, "", "", "", "", "0");
		// 先判断当前用户有无权限执行该操作
		setSaveBtnStatu();

		getSystime();
	}

	private void initDate() {


		// 初始化列表中第一个数据为“请选择”
		mBmmcList.add("请选择\nVui lòng chọn");
		// 获取权限
		mSaveQX = (String) SharedPreUtil.getValue(this, SharedPreUtil.CM0140202, "");
		// mSaveQX="0";
	}

	private void initView() {
		mDateLl = (LinearLayout) findViewById(R.id.query_dateLl);
		mDateTv = (TextView) findViewById(R.id.query_dateTv);
		mJobNumEt = (EditText) findViewById(R.id.query_jobNumEt);
		mMachineNoEt = (EditText) findViewById(R.id.query_machineNoEt);
		//mBmmcSp = (Spinner) findViewById(R.id.query_bmmcSp);
		mClassesSp = (Spinner) findViewById(R.id.query_classesSp);

		mCheckBox = (CheckBox) findViewById(R.id.query_CheckBox);
		mQueryBtn = (Button) findViewById(R.id.query_queryBtn);
		mSaveBtn = (Button) findViewById(R.id.query_saveBtn);
		// mBackBtn = (Button) findViewById(R.id.query_backBtn);
		mCountTv = (TextView) findViewById(R.id.query_countTv);
		mCountTv2 = (TextView) findViewById(R.id.query_countTv2);
		mListView = (ListView) findViewById(R.id.query_listView);
		nodateImg = (ImageView) findViewById(R.id.query_nodateImg);

		// 设置车间下拉框适配器 数据来源于访问服务器的数据字典
		mBmmcSpAdapter = new ArrayAdapter<String>(this, R.layout.spinner_item, mBmmcList);
		mBmmcSpAdapter.setDropDownViewResource(R.layout.spinner_drop_item);
		//mBmmcSp.setAdapter(mBmmcSpAdapter);

		// 设置班次下拉框适配器 数据来源于arrays.xml文件
		ArrayAdapter<String> classesSpAdapter = new ArrayAdapter<String>(this, R.layout.spinner_item, getResources().getStringArray(R.array.classes));
		classesSpAdapter.setDropDownViewResource(R.layout.spinner_drop_item);
		mClassesSp.setAdapter(classesSpAdapter);
		// 设置显示当前日期
		mDateTv.setText(dateFormat_EN.format(Calendar.getInstance().getTime()));
		// 设置分割线
		mListView.setDivider(getResources().getDrawable(R.color.line));
		// 设置分割线高度
		mListView.setDividerHeight(1);
		mAdapter = new QueryListAdapter(this, mProductList);
		mListView.setAdapter(mAdapter);
	}

	/**
	 * 获取时间
	 */
	private void getSystime() {
		showWait();
		RequestServiceImpl.getDateTime(mMIPHandler, IServiceImpl.GET_TIME);
	}

	/**
	 * 初始化事件
	 */
	private void initEvent() {
		mDateLl.setOnClickListener(this);
		mQueryBtn.setOnClickListener(this);
		mSaveBtn.setOnClickListener(this);
		// mBackBtn.setOnClickListener(this);
		mJobNumEt.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				mAdapter.setFocusIndex(-1);
				return false;
			}
		});
		mMachineNoEt.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				mAdapter.setFocusIndex(-1);
				return false;
			}
		});
		mAdapter.setOnCheckClickListener(new onCheckClickListener() {

			@Override
			public void onClick(int position, boolean isChecked) {
				mProductList.get(position).isChecked = isChecked;
				mCount = 0;
				for (int i = 0; i < mProductList.size(); i++) {
					if (mProductList.get(i).isChecked == true) {
						mCount++;
					}
				}
				mCountTv.setText("已选择\n" + mCount + "项");
				mCountTv2.setText("Đã chọn" + mCount + "mục");
				// 设置保存按钮状态
				setSaveBtnStatu();
			}
		});
		mCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if (isChecked) {
					mStandardQuota = "1";
				} else {
					mStandardQuota = "0";
				}
			}
		});
	}

	/**
	 * 设置保存按钮的状态
	 */
	protected void setSaveBtnStatu() {
		if ("1".equals(mSaveQX) && mCount > 0) {
			mSaveBtn.setEnabled(true);
			mSaveBtn.setBackground(getResources().getDrawable(R.drawable.btn_corner_green_dark1));

		} else {
			mSaveBtn.setEnabled(false);
			mSaveBtn.setBackground(getResources().getDrawable(R.drawable.btn_corner_gray1));
		}

	}

	/**
	 * 获取车间下拉框值
	 */
	private void selectDict() {
		showWait();
		RequestServiceImpl.selectDict(mMIPHandler, IServiceImpl.SELECTDICT, TableNo.BMMC);
	}

	/**
	 * 准备获取查询产量列表  
	 * 2017年8月16日修改：车间必须选择
	 */
	private void startGetQueryList() {
		String date = mJobDate;
		String machineNo = mMachineNoEt.getText().toString();
		String jobNum = mJobNumEt.getText().toString();
		String bmmc="";
		String classes;
//		if (mBmmcSp.getSelectedItemPosition() == 0) {
//			bmmc = "";
//			SimpleDialog.show(this, "请选择车间！");
//			return;
//		} else {
//			bmmc = mBmmcSp.getSelectedItem().toString();
//		}
		if (mClassesSp.getSelectedItemPosition() == 0) {
			classes = "";
		} else {
			classes = mClassesSp.getSelectedItem().toString();
		}
		//截取签名的中文，不要越南文
		if(!TextUtils.isEmpty(classes)&&classes.contains("(")){
			classes=classes.substring(0,classes.indexOf("("));
		}
		getQueryList(date, bmmc, machineNo, jobNum, classes,	mStandardQuota);
	}

	/**
	 * 查询产量列表
	 * 
	 * @param jobDate
	 * @param machineNo
	 * @param jobNum
	 * @param classes
	 */
	private void getQueryList(String jobDate, String bmmc, String machineNo, String jobNum, String classes, String standardQuota) {
		showWait();
		String userBean = (String) SharedPreUtil.getValue(this, SharedPreUtil.USERBEAN, "");
		RequestServiceImpl.getQuerylist(mMIPHandler, IServiceImpl.GETQUERYLIST_R, userBean,jobDate, bmmc, machineNo, jobNum, classes, standardQuota);
	}

	/***
	 * 准备进行更新保存操作
	 */
	private void startUpdateQueryList() {

		// 每次保存之前都要进行清空，可能存在上一次保存失败的情况下，数据还存在list中
		mSaveProductList.clear();
		for (int i = 0; i < mProductList.size(); i++) {
			if (mProductList.get(i).isChecked) {
				// 添加到需要保存的列表中
				mSaveProductList.add(mProductList.get(i));
			}
		}

		if (mProductList.size() == 0) {
			SimpleDialog.show(this, "当前列表为空，请添加数据！\nBảng trước trống, vui lòng nhập dữ liệu");
			stopWait();
			return;
		}

		if (mSaveProductList.size() == 0) {
			SimpleDialog.show(this, "请勾选需要保存的数据！\nVui lòng chọn dữ liệu cần lưu");
			stopWait();
			return;
		}

		for (ProductQueryEntity product : mSaveProductList) {
			if (TextUtils.isEmpty(product.STANDARD_SPEED)) {
				SimpleDialog.show(this, "标准车速不能为空！\nTốc độ máy tiêu chuẩn không được để trống ");

				return;
			}
			if (TextUtils.isEmpty(product.STANDARD_RATE)) {
				SimpleDialog.show(this, "标准转数不能为空\nSố vòng tiêu chuẩn  không được để trống ");

				return;
			}
			if (TextUtils.isEmpty(product.STANDARD_ONJOB)) {
				SimpleDialog.show(this, "标准开台不能为空！\nTiêu chuẩn chạy máy  không được để trống ");

				return;
			}
			if (TextUtils.isEmpty(product.STANDARD_QUOTA)) {
				SimpleDialog.show(this, "标准定额不能为空！\nĐịnh mức tiêu chuẩn không được để trống");

				return;
			}
		}
		updateQueryList(mSaveProductList);
	}

	/**
	 * 更新保存数据
	 */
	private void updateQueryList(List<ProductQueryEntity> productList) {
		showWait();
		String userBean = (String) SharedPreUtil.getValue(this, SharedPreUtil.USERBEAN, "");
		RequestServiceImpl.updateQuerylist(mMIPHandler, IServiceImpl.UPDATEQUERYLIST_R, userBean, productList);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.query_dateLl:
			setDate();
			break;
		case R.id.query_queryBtn:
			startGetQueryList();
			break;
		case R.id.query_saveBtn:
			startUpdateQueryList();
			break;
		// case R.id.query_backBtn:
		// this.finish();
		// break;

		default:
			break;
		}

	}

	/**
	 * 检查listview是否为空
	 */
	private void checkListview() {
		if (mProductList.size() > 0) {
			mListView.setVisibility(View.VISIBLE);
		} else {
			mListView.setVisibility(View.GONE);
		}
	}

	/**
	 * 设置日期
	 */
	private void setDate() {
		// 初始化日历信息
		Calendar calendar = Calendar.getInstance();
		// 获取当前年月日
		int year = calendar.get(Calendar.YEAR);
		int month = calendar.get(Calendar.MONTH);
		final int day = calendar.get(Calendar.DAY_OF_MONTH);
		Log.d("setDate", year + "-" + month + "-" + day);
		/**
		 * context：当前上下文； callback：OnDateSetListener日期改变监听器； year：初始化的年；
		 * monthOfYear：初始化的月（从0开始计数，所以实际应用时需要加1）； dayOfMonth：初始化的日；
		 */
		try{
			String[] time= mJobDate.split("-");
			DatePickerDialog datePickerDialog = new DatePickerDialog(this, mOnDateSetListenernew,Integer.parseInt(time[0]), Integer.parseInt(time[1])-1, Integer.parseInt(time[2]));
			datePickerDialog.show();
		}catch (Exception e){

		}

	}

	/**
	 * 日期选择监听器
	 */
	OnDateSetListener mOnDateSetListenernew = new OnDateSetListener() {
		@Override
		public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
			String date = year + "-" + String.format("%02d", month + 1) + "-" + String.format("%02d", dayOfMonth) ;
			
			mDateTv.setText(date);
			
			mJobDate = year + "-" + String.format("%02d", month + 1) + "-" + String.format("%02d", dayOfMonth);
		}
	};

	@Override
	public void onPostHandle(int requestType, Object objBody, boolean error) throws Exception {
		stopWait();
		String msg = "";
		String opt = "";
		if (error) {
			switch (requestType) {
			case IServiceImpl.GETQUERYLIST_R:

				try {
					JSONObject jsonObj = new JSONObject((String) objBody);
					msg = jsonObj.optString("MSG_INFO");
					opt = jsonObj.optString("OPT_FLAG");
					if ("0".equals(opt)) {
						// 解析获取page数组
						String page = jsonObj.optString("page");
						Gson gson = new Gson();
						List<ProductQueryEntity> list = gson.fromJson(page, new TypeToken<List<ProductQueryEntity>>() {
						}.getType());
						mProductList.clear();
						mProductList.addAll(list);
						mAdapter.notifyDataSetChanged();
						checkListview();

					} else if ("1".equals(opt)) {
						SimpleDialog.show(this, msg);

					}

				} catch (Exception e) {
					e.printStackTrace();

				}
				break;
			case IServiceImpl.UPDATEQUERYLIST_R:

				try {
					JSONObject jsonObj = new JSONObject((String) objBody);
					msg = jsonObj.optString("MSG_INFO");
					opt = jsonObj.optString("OPT_FLAG");
					if ("0".equals(opt)) {
						SimpleDialog.show(this, "您已成功保存" + mSaveProductList.size() + "条数据！"+"\n{Đã lưu thành công "+mSaveProductList.size() +" số liệu");
						mSaveProductList.clear();
						// 保存成功后重新获取列表进行刷新
						startGetQueryList();

					} else if ("1".equals(opt)) {
						SimpleDialog.show(this, msg);

					} else if ("2".equals(opt)) {
						SimpleDialog.show(this, msg);

					}

				} catch (Exception e) {
					e.printStackTrace();
				}
				break;
			case IServiceImpl.SELECTDICT:

				try {
					Gson gson = new Gson();
					List<SpinnerEntity> spinnerEntityList = gson.fromJson(objBody.toString(), new TypeToken<List<SpinnerEntity>>() {
					}.getType());
					for (SpinnerEntity spinnerEntity : spinnerEntityList) {
						mBmmcList.add(spinnerEntity.fieldText);
					}
					mBmmcSpAdapter.notifyDataSetChanged();
				} catch (Exception e) {
					e.printStackTrace();

				}
				break;

				case IServiceImpl.GET_TIME:
					try {
						if(objBody.toString().length()>10){
							mJobDate=objBody.toString().substring(0,10);
							mDateTv.setText(mJobDate);
						}else{
							mJobDate = dateFormat_EN.format(Calendar.getInstance().getTime());
						}
					} catch (Exception e) {
						e.printStackTrace();
						mJobDate = dateFormat_EN.format(Calendar.getInstance().getTime());
					}
					break;
			}


		} else {
			SimpleDialog.show(this, objBody.toString());
//			switch (requestType) {
//			case IServiceImpl.GETQUERYLIST_R:
//				toast("查询失败！");
//				break;
//			case IServiceImpl.UPDATEQUERYLIST_R:
//				toast("保存失败！");
//				break;
//			case IServiceImpl.SELECTDICT:
//				toast("获取失败！");
//				break;
//
//			}

		}

	}

}
